package com.jsonpfy.operations;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.repackaged.org.json.JSONArray;



/** 
 * List the data of a particular kind in the datastore.
 * 
 * @
 * @Entity 
 */

public class List {

	private static JSONArray jsonQuery(Query q) {

		JSONArray jsonArray = new JSONArray();

		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		PreparedQuery pq = datastore.prepare(q);

		for (Entity result : pq.asIterable()) {

			jsonArray.put(ConvertEntityToJson.getJson(result));
		}

		return jsonArray;
	}

	public static JSONArray jsonList(String kind, String sortField,
			String sortDirection) {

		Query q = new Query(kind);

		jsonListSort(q, sortField, sortDirection);

		return jsonQuery(q);
	}

	public static JSONArray jsonListFilter(String kind, String filterField,
			String filterValue, String sortField, String sortDirection) {

		Query q = new Query(kind);

		if (filterField != null) {

			q.addFilter(
					filterField,
					com.google.appengine.api.datastore.Query.FilterOperator.EQUAL,
					filterValue);
		}

		jsonListSort(q, sortField, sortDirection);

		return jsonQuery(q);
	}

	public static JSONArray jsonListFilterKey(String kind,
			String filterKeyField, String filterKeyKind, String filterKeyValue,
			String sortField, String sortDirection) {

		Query q = new Query(kind);

		if (filterKeyField != null) {

			q.addFilter(
					filterKeyField,
					com.google.appengine.api.datastore.Query.FilterOperator.EQUAL,
					KeyFactory.createKey(filterKeyKind, filterKeyValue));
		}

		jsonListSort(q, sortField, sortDirection);

		return jsonQuery(q);
	}

	public static void jsonListSort(Query q, String sortField,
			String sortDirection) {

		if (sortField != null) {

			if (sortDirection != null) {

				q.addSort(sortField, SortDirection.DESCENDING);

			} else {

				q.addSort(sortField);
			}
		}
	}

}